/*
 *       Copyright (c) 2008-2009 All rights reserved
 *               Asemantics S.r.l
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        Asemantics S.r.l."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    This product includes software developed by Asemantics S.r.l.
 *    the Semantic Web company, Rome, London, Leiden and its contributors.
 *
 * 5. Neither the name of the company nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */


package com.asemantics.poco.persistence;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import org.apache.log4j.Logger;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import com.asemantics.poco.utils.BeanComparator;
import com.asemantics.poco.utils.ComparisonReport;

/**
 * Base class to test object lifecycle.
 *
 * @author Michele Mostarda ( michele.mostarda@gmail.com )
 */
public abstract class BasePersistorTestCase<T,II,IO> {

    private static final int CREATED_OBJECTS = 5;

    private final Logger LOGGER = Logger.getLogger( this.getClass() );

    protected static long disambiguer;

    private Type objectType;

    private Class<T> objectRawType;

    private Persistor persistor;

    private II lastPersistedID;

    /**
     * Constructor.
     */
    public BasePersistorTestCase() {
        Type superclass = getClass().getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing objectType parameter.");
        }

        this.objectType = ((ParameterizedType) superclass).getActualTypeArguments()[0]; // T
        if (this.objectType instanceof Class<?>) {
            this.objectRawType = (Class<T>) this.objectType;
        } else {
            this.objectRawType = (Class<T>) ((ParameterizedType) this.objectType).getRawType();
        }
    }

    public abstract T createObject();

    /**
     * Returns the object identifier on the basis of the object itself and the last identifier returned
     * by the Persistor#persist() method.

     * @param lastID the ID of the last generated object.
     * @param in input object.
     * @return object identifier.
     */
    public abstract IO getId(II lastID, T in);

    /**
     * @return number of objects to be created by #testPersistObject().
     */
    public int numberOfCreatedObjects() {
        return CREATED_OBJECTS;
    }

    /**
     * Retrieve the last persisted object.
     * @return
     */
    @DataProvider
    Object[][] retrieveLastObject() {
        try {
            List<T> result = persistor.retrieveAll(getObjectRawType());
            for (int i = result.size() - 1; i >= 0; i--) {
                if (result.get(i).getClass().equals(getObjectRawType())) {
                    return new Object[][]{{
                          result.get(i)
                    }};
                }
            }
            throw new RuntimeException("Cannot find the last object of type " + getObjectRawType());

        } catch (PersistorException pe) {
            throw new RuntimeException("Error while retrieving first object.");
        }
    }

    @BeforeClass
    public void setUp() throws ConfigurationException {
        Configuration teConfiguration = Configuration.createConfiguration("/datanucleus.properties");
        persistor = new PersitorDefaultImpl( teConfiguration );
    }

    @AfterClass
    public void tearDown() {
        persistor = null;
    }

    /**
     * Persists an object in the storage.
     *
     * @throws PersistorException
     */
    @Test
    public void testPersistObject() throws PersistorException {
        for(int i = 0; i < numberOfCreatedObjects(); i++) {
            T obj = createObject();

            final long startTime = System.currentTimeMillis();
            lastPersistedID = persistor.<T,II>persist( obj );
            log( "Persist object time: " +  (System.currentTimeMillis() - startTime)  + "ms" );
        }
    }

    /**
     * Retrieves all the objects from the storage.
     *
     * @throws PersistorException
     */
    @Test(alwaysRun = true, dependsOnMethods = "testPersistObject")
    public void testRetrieveObjects() throws PersistorException {
        final long startTime = System.currentTimeMillis();
        List<T> objs = persistor.retrieveAll( getObjectRawType() );
        log( "Retrieve objects time: " +  (System.currentTimeMillis() - startTime) + "ms" );

        for(T obj : objs) {
            log(getObjectRawType().getName() + ": " + obj);
        }

        assert objs.size() > 0 : "Expected at least the created object.";
    }

    /**
     * Retrieves a specific object using an identifier from the storage.
     *
     * @param in input object to be retieved.
     * @throws PersistorException
     */
    @Test( alwaysRun = true, dependsOnMethods = {"testPersistObject"}, dataProvider = "retrieveLastObject")
    public void testRetrieveObject(T in) throws PersistorException {
        final IO id = getId( lastPersistedID, in);

        final long startTime = System.currentTimeMillis();
        T obj = persistor.<T,IO>retrieve(id);
        log( "Retrieve object time: " +  (System.currentTimeMillis() - startTime) + "ms" );

        log(getObjectRawType().getName() + ": " + obj);

        assert obj != null : "Expected object.";
        assert id.equals( getId( lastPersistedID, obj ) ) : "Expected same IDs.";

        // Compare last object with retrieved object.
        ComparisonReport comparisonReport = BeanComparator.compareBeans( in, obj );
        log( "Comparison Report:" + comparisonReport.toString() );
        assert ! comparisonReport.isDifferent() : "Expected to be equal.";
    }

    /**
     * Deletes an object from the storage.
     *
     * @param in input object to be deleted.
     * @throws PersistorException
     */
    @Test(alwaysRun = true, dependsOnMethods = {"testRetrieveObject"}, dataProvider = "retrieveLastObject")
    public void testDeleteObject(T in) throws PersistorException {
        final long startTime = System.currentTimeMillis();
        persistor.delete( getId( lastPersistedID, in) );

        log( "Delete object time: " +  (System.currentTimeMillis() - startTime)  + "ms" );
    }

    protected static String createUniqueKey(String prefix) {
        return prefix + System.currentTimeMillis() + "." + (disambiguer++) ;
    }

    protected final Type getObjectType() {
        return this.objectType;
    }

    protected final Class<T> getObjectRawType() {
        return objectRawType;
    }

    protected void log(String msg) {
        LOGGER.debug(msg);
    }

}